#!/usr/local/bin/pl -g serql_welcome -L0 -G0 -T0 -s

% Needs SeRQL in the path

:- dynamic
        user:file_search_path/2.
:- multifile
        user:file_search_path/2.

:- prolog_load_context(directory, Dir),
   atom_concat(Dir,'/SeRQL',SeRQLDir),
   asserta(user:file_search_path(serql, SeRQLDir)).

:- load_files([ serql(load)
              ],
              [ silent(true)
              ]).

:- use_module(library('rdf_write')).

% P2R code

:- use_module('p2r/p2r_entailment').




% Handcrafted mappings

:- use_module('tsv/tsv_mapping').
%:- use_module('toc/toc_mapping').
:- use_module('dic/dic_mapping').



%%%%%%%%%%%%%%%%%%%%%
directory(Dir,URI) :-
	tsv_mapping:directory(Dir,URI).
directory(Dir,URI) :- 
	toc_mapping:directory(Dir,URI).
directory(Dir,URI) :-
	dic_mapping:directory(Dir,URI).

	

uri_to_dir(A,Dir) :-
        atomic(A),
        concat_atom(T,'#',A),
        cut_last(T,T2),
        concat_atom(T2,B),
        concat_atom(L,'/',B),
        cut_from('riese.joanneum.at',L,L2),
        concat_atom(['fs'|L2],'/',Dir).

% heh - certainly the most obscure way of creating directories recursively :-)
create(Dir) :-
        ((exists_directory(Dir),!);\+create_n(Dir)).
create_n(Dir) :-
        concat_atom(L,'/',Dir),
        sub_list(L,SL),
        concat_atom(SL,'/',SubDir),
        ((exists_directory(SubDir),fail);(\+exists_directory(SubDir),make_directory(SubDir),fail)).
sub_list([H|_],[H]).
sub_list([H|T1],[H|T2]) :- sub_list(T1,T2).
cut_from(Item,[Item|T],T) :- !.
cut_from(Item,[_|T1],T2) :- cut_from(Item,T1,T2).
cut_last(List,List2) :-
        reverse(List,RL),
        cut_first(RL,RL2),
        reverse(RL2,List2).
cut_first([_|T],T).
%%%%%%%%%%%%%%%%%%%%%


dump_ffs :- 
	writeln(' - Dumping filesystem image...'),
	forall((directory(Dir,_),create(Dir)),
		(
			format(' - Processing directory ~w\n',[Dir]),
			bagof(URI,directory(Dir,URI),URIs),
			bagof(rdf(URI,P,O),(member(URI,URIs),p2r_entailment:rdf(URI,P,O)),Triples),
			atom_concat(Dir,'/content.rdf',File),
			format(' - Creating ~w\n',[File]),
			open(File,write,S,[encoding(utf8)]),
			rdf_write_xml(S,Triples),
			close(S)
		)
	),
	writeln(' - Done!').


